import React, { useEffect, useRef } from 'react';
import { eventTrack } from '@/utils/track';
import { connect } from 'umi';
import { Form, Table, Popconfirm, Card, Button, Divider } from 'antd';
import { utils } from 'vv-frontend-components';
import Pagination from '@/components/Pagination';
import TableFilter from '@/components/TableFilter';
// import isEmpty from 'lodash/isEmpty';
import { history } from 'umi';
import LinkTo from '@/components/LinkTo';
// import CompanyDepartPermission from '@/components/CompanyDepartPermission';
// AuthComponent AuthCode权限控制
import AuthCode from '@/utils/auth/AuthCode';
import AuthComponent from '@/utils/auth/AuthComponent';
// import CandidateSearchForm from './SearchForm';
// import Filter from './Filter'; // 发起用人组织机构筛选
// import { TreeSelectForm } from '@/components/UserForm';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import CompanyDepartPlus from '@/containers/select/CompanyDepartPlus';

// import {
//     getTypeList,
//     getCompanyTree
// } from '@/services/components/userform';
// import './index.less';

const List = ({ form, loading, holidaymanagement, dispatch, location, route }) => {
    // 按钮权限控制
    const { authCode } = new AuthCode(route.code);
    // 过滤高级搜索空格
    const { deepTrim } = utils;
    const { query } = location;
    const {
        pagination,
        holidayList: tableData,
        // orderBy,
        leaveUnit,
        leaveTimeway,
        isMoney,
        balanceRule,
        leaveUnitlist,
        leaveTimewaylist,
        isMoneylist,
        balanceRulelist
    } = holidaymanagement;
    // 获取登陆人公司id
    // 获取参数
    const { getFieldsValue } = form;
    const { getFieldDecorator } = form;

    const [filter, setFilter] = React.useState('');
    const getSearchData = pageNo => {
        // 方法自动获取高级搜索表单参数
        const { companyidSearch } = getFieldsValue();
        // 接口传参参数
        const payload = {
            leaveUnit: leaveUnit.toString(),
            leaveCountType: leaveTimeway.toString(),
            salaryCountType: isMoney.toString(),
            provideBalanceType: balanceRule.toString(),
            pageNo: pageNo || pagination.current,
            pageSize: pagination.pageSize,
            // 高级搜索字段
            companyCode: companyidSearch?.companyId
        };
        // console.log('payload', payload);
        return payload;
    };
    // 接口请求
    const fetchList = (ctx = {}) => {
        const { pageNo = null } = ctx;
        if (balanceRule.toString() === 'no_balance_limit') {
            dispatch(
                deepTrim({
                    type: 'holidaymanagement/fetchHolidayList',
                    payload: {
                        ...getSearchData(pageNo),
                        provideBalanceType: '',
                        openState: '0'
                    }
                })
            );
        } else {
            dispatch(
                deepTrim({
                    type: 'holidaymanagement/fetchHolidayList',
                    payload: {
                        ...getSearchData(pageNo)
                    }
                })
            );
        }
    };

    // 删除列表
    const confirm = async id => {
        await dispatch({
            type: 'holidaymanagement/holidayDelete',
            payload: {
                id
            },
            success: () => {
                // 成功刷新页面
                fetchList({ pageNo: 1 });
            }
        });
        // message.success('click on Yes');
    };
    // 列表项
    const columns = [
        {
            title: '假期名称',
            dataIndex: 'leaveName',
            key: 'leaveName',
            // width: 200,
            render(text) {
                return (
                    <span
                        style={{
                            display: 'inline-block',
                            maxWidth: 200,
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            verticalAlign: ' text-bottom'
                        }}
                        title={text}
                    >
                        {text}
                    </span>
                );
            }
        },
        {
            title: '请假单位',
            dataIndex: 'leaveUnitName',
            key: 'leaveUnitName',
            filters: leaveUnitlist,
            // ...filterValuesCfg,
            filteredValue: typeof query.leaveUnit !== 'undefined' ? query.leaveUnit : leaveUnit,
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            width: 200
        },
        {
            title: '计算请假时长方式',
            dataIndex: 'leaveCountTypeName',
            key: 'leaveCountTypeName',
            filters: leaveTimewaylist,
            // ...filterValuesCfg,
            filteredValue: typeof query.leaveTimeway !== 'undefined' ? query.leaveTimeway : leaveTimeway,
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            width: 200
        },
        {
            title: '是否带薪',
            dataIndex: 'salaryCountTypeName',
            key: 'salaryCountTypeName',
            filters: isMoneylist,
            // ...filterValuesCfg,
            filteredValue: typeof query.isMoney !== 'undefined' ? query.isMoney : isMoney,
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            width: 200
        },
        {
            title: '余额规则',
            dataIndex: 'provideBalanceTypeName',
            key: 'provideBalanceTypeName',
            filters: balanceRulelist,
            // ...filterValuesCfg,
            filteredValue: typeof query.balanceRule !== 'undefined' ? query.balanceRule : balanceRule,
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            width: 180,
            render(text, record) {
                return <span>{record.openState === '0' ? '不限制余额' : text}</span>;
            }
        },
        {
            title: '操作',
            dataIndex: '',
            key: '',
            render(text, record) {
                return (
                    <div>
                        <AuthComponent code={authCode('edit')}>
                            <LinkTo
                                // 埋点
                                onClick={async (e, url) => {
                                    await eventTrack({
                                        eventName: 'personnel_management_attendance_holidayManagement_edit_click',
                                        eventProps: {
                                            label: '假期管理-编辑'
                                        }
                                    });
                                    history.push(url);
                                }}
                                to="/office/personnelManagement/attendance/holidayManagement/editholiday"
                                query={{
                                    action: 'edit',
                                    id: record.id,
                                    editleaveCode: record.leaveCode
                                }}
                                className="marginR dividingline"
                            >
                                编辑
                            </LinkTo>
                            <Divider type="vertical" />
                        </AuthComponent>
                        <AuthComponent code={authCode('delete')}>
                            <Popconfirm
                                title="你确定删除吗?"
                                onConfirm={() => {
                                    confirm(record.id);
                                    // 埋点
                                    eventTrack({
                                        eventName:
                                            'personnel_management_attendance_holidayManagement_delete_submit_click',
                                        eventProps: {
                                            label: '假期管理-删除-确定'
                                        }
                                    });
                                }}
                                onCancel={() => {
                                    // 埋点
                                    eventTrack({
                                        eventName:
                                            'personnel_management_attendance_holidayManagement_delete_cancel_click',
                                        eventProps: {
                                            label: '假期管理-删除-取消'
                                        }
                                    });
                                }}
                                // onCancel={cancel}
                                okText="确定"
                                cancelText="取消"
                            >
                                <a
                                    href="#"
                                    disabled={record.deleteButton ? null : 'disabeled'}
                                    onClick={() => {
                                        eventTrack({
                                            eventName: 'personnel_management_attendance_holidayManagement_delete_click',
                                            eventProps: {
                                                label: '假期管理-删除'
                                            }
                                        });
                                    }}
                                >
                                    删除
                                </a>
                            </Popconfirm>
                        </AuthComponent>
                    </div>
                );
            }
        }
    ];

    // 排序功能
    const tableChange = (newPagination, filters = {}) => {
        dispatch({
            type: 'holidaymanagement/save',
            payload: {
                leaveUnit: filters.leaveUnitName || filter.leaveUnitName || [], // 请假单位
                leaveTimeway: filters.leaveCountTypeName || filter.leaveCountTypeName || [], // 计算时长方式
                isMoney: filters.salaryCountTypeName || filter.salaryCountTypeName || [], // 是否带薪
                balanceRule: filters.provideBalanceTypeName || filter.provideBalanceTypeName || [], // 余额规则
                pagination: {
                    ...holidaymanagement.pagination,
                    ...newPagination
                }
            }
        });
        if (filters && JSON.stringify(filter) !== JSON.stringify(filters)) {
            setFilter(filters);
            dispatch({
                type: 'holidaymanagement/save',
                payload: {
                    pagination: {
                        ...holidaymanagement.pagination,
                        pageSize: pagination.pageSize,
                        current: 1
                    }
                }
            });
        }
    };
    // 加载阶段、状态筛选列数据
    useEffect(() => {
        dispatch({
            type: 'holidaymanagement/fetchFilterList',
            payload: {
                dictCode: 'leaveUnitType'
            }
        });
        dispatch({
            type: 'holidaymanagement/fetchFilterList',
            payload: {
                dictCode: 'leaveCountType'
            }
        });
        dispatch({
            type: 'holidaymanagement/fetchFilterList',
            payload: {
                dictCode: 'salaryCountType'
            }
        });
        dispatch({
            type: 'holidaymanagement/fetchFilterList',
            payload: {
                dictCode: 'validRuleSelectType'
            }
        });
    }, []);
    // 组件卸载时候 清空表单请求参数（高级搜索内容、分页、排序字段）
    useEffect(
        () => () => {
            dispatch({
                type: 'holidaymanagement/save',
                payload: {
                    pagination: {
                        ...pagination,
                        pageSize: 10,
                        current: 1
                    },
                    holidayList: [],
                    leaveUnit: [], // 请假单位
                    leaveTimeway: [], // 计算时长方式
                    isMoney: [], // 是否带薪
                    balanceRule: [] // 余额规则
                }
            });
        },
        []
    );
    // 每当分页数、页面条数、排序、筛查项改变时均应该重新请求表格数据
    useEffect(() => {
        fetchList();
    }, [pagination.pageSize, pagination.current, leaveUnit, leaveTimeway, isMoney, balanceRule]);

    const tableRef = useRef();
    return (
        <PageHeaderWrapper>
            <Card
                title="假期管理"
                extra={
                    <AuthComponent code={authCode('save')}>
                        <Button
                            type="primary"
                            onClick={async () => {
                                // 埋点
                                await eventTrack({
                                    eventName: 'personnel_management_attendance_holidayManagement_add_click',
                                    eventProps: {
                                        label: '添加假期'
                                    }
                                });
                                history.push({
                                    pathname: '/office/personnelManagement/attendance/holidayManagement/addholiday'
                                });
                            }}
                        >
                            添加假期
                        </Button>
                    </AuthComponent>
                }
            >
                <Form
                    layout="inline"
                    style={{ marginBottom: 12 }}
                    onSubmit={e => {
                        e.preventDefault();
                        console.log(2);
                        fetchList({ pageNo: 1 });
                        eventTrack({
                            eventName: 'personnel_management_attendance_holidayManagement_search_click',
                            eventProps: {
                                key_works: JSON.stringify(form.getFieldsValue())
                            }
                        });
                    }}
                >
                    <Form.Item label="机构">
                        {getFieldDecorator('companyidSearch')(
                            <CompanyDepartPlus hideOrg />
                        )}
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            搜索
                        </Button>
                    </Form.Item>
                </Form>
                <div ref={tableRef}>
                    <Table
                        bordered={false}
                        columns={columns}
                        loading={loading.models.holidaymanagement}
                        scroll={{
                            x: 1200
                        }}
                        dataSource={tableData}
                        rowKey="holidaymanegement"
                        onChange={tableChange}
                        pagination={false}
                    />
                    <Pagination
                        {...pagination}
                        onChange={tableChange}
                        filters={filter}
                        loading={loading.models.holidaymanagement}
                    />
                </div>
            </Card>
        </PageHeaderWrapper>
    );
};
export default connect(({ holidaymanagement, loading }) => ({
    holidaymanagement,
    loading
}))(Form.create()(List));
